<!--
 * @Descripttion: 岗位选择
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2021-06-17 15:56:37
 * @LastEditTime: 2021-08-09 10:30:39
 * @Param {Void} 
 * @Example <post-select></post-select>
 * @FilePath: \cscec-pms-admin\src\layouts\PostSelect.vue
-->
<template>
  <div
    class="post-select"
    @click="visible = true"
  >
    <a-popover
      v-model="popover"
      title="当前岗位"
      trigger="hover"
      arrow-point-at-center
      auto-adjust-overflow
      placement="bottomRight"
    >
      <template slot="content">
        <p>{{ currentPostName }}</p>
      </template>
      <BaseSvgIcon
        class="icon-item"
        icon="post"
        color="red"
      />
    </a-popover>
    <div
      :class="{'post-select-container-active':visible}"
      class="post-select-container"
    >
      <div
        ref="wrapper"
        class="post-select-wrapper"
        @click="maskClick"
      >
        <div class="post-select-content">
          <!-- <img
            src="~@/assets/gateway/Frame(14).png"
            alt=""
          > -->
          <p>选择岗位信息</p>
          <div
            v-if="loading"
            class="post-select-radio"
          >
            <a-spin size="large" />
          </div>
          <div
            v-else-if="postsList.length > 0"
            class="post-select-radio"
          >
            <a-radio-group v-model="currentPost">
              <a-radio
                v-for="item in postsList"
                :key="item.id"
                :value="item.id"
                :title="item.pname"
              >
                {{ item.pname }}
              </a-radio>
            </a-radio-group>
          </div>
          <div
            v-else
            class="post-select-empty"
          >
            <a-empty :image="simpleImage">
              <span slot="description">暂无岗位信息</span>
            </a-empty>
          </div>
          <button
            class="post-select-submit"
            @click="handleConfirmPost"
          >
            <template v-if="btnLoading">
              <a-icon type="loading" />
              <span>确认</span>
            </template>
            <template v-else>
              <span>确认</span>
            </template>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { Popover, Empty } from 'ant-design-vue'
import Vue from 'vue'
import { getPostParentName, changeCurrentPost, getCurrentUserBranchCom3, getProjectIdByOrgId } from '@/api/commons.js'

export default {
  name: 'PostSelect',
  props: {
    popoverVisible: {
      type: Boolean,
      default: false
    }
  },
  components: {
    AEmpty: Empty,
    APopover: Popover
  },
  inject: ['reload'],
  data() {
    return {
      // 弹框显示
      visible: false,
      // 气泡显示隐藏
      popover: this.popoverVisible,
      // 空图片
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      // 岗位列表
      postsList: [],
      // 当前岗位id
      currentPost: '',
      // 当前岗位信息
      currentPostInfo: {},
      // 列表加载
      loading: true,
      // 按钮加载
      btnLoading: false,
      // 角色信息
      userInfo: {}
    }
  },
  watch: {
    visible: {
      handler(newV) {
        if (newV) {
          this.init()
        } else {
          this.reset()
        }
      }
    },
    popoverVisible: {
      handler(newV) {
        this.popover = newV
      }
    },
    popover: {
      handler(newV) {
        this.$emit('update.popoverVisible', newV)
      }
    }
  },
  computed: {
    currentPostName() {
      const currentPost = this.postsList.find((el) => el.id === this.userInfo.currentPost.postId)
      return currentPost?.pname || '暂无岗位信息'
    }
  },
  created() {
    this.init()
  },
  methods: {
    /**
     * 清除额外的缓存
     */
    clearExtraCache() {
      // 施工进度总计划列表到实施管理页面的标识，用于判断项目部的人员是否直接进入实施管理页面
      sessionStorage.removeItem('setPD')
      // 待读消息相关缓存
      this.$store.commit('messageInfo/REMOVE_MESSAGE_COUNT')
      // 页码缓存
      sessionStorage.setItem('cachePagination', JSON.stringify({}))
    },
    /**
     * @description: 初始化
     * @param {Void}
     * @return {Void}
     */
    init() {
      this.userInfo = JSON.parse(sessionStorage.getItem('ycloud-user_info'))
      this.currentPost = this.userInfo.currentPost.postId
      this.getPostList()
    },
    /**
     * @description: 获取岗位信息
     * @param {Void}
     * @return {Void}
     */
    async getPostList() {
      const { data } = await getPostParentName({ id: this.userInfo.id })
      this.postsList = data || []
      sessionStorage.setItem('postsList',JSON.stringify(this.postsList))
      this.loading = false
    },
    /**
     * @description: 确认岗位
     * @param {Void}
     * @return {Void}
     */
    async handleConfirmPost() {
      if (!this.currentPost) {
        this.$message.warning('请选择岗位')
        return
      }
      if (this.btnLoading) return
      this.btnLoading = true
      const USERINFO = {
        ...this.userInfo,
        currentPost: this.postsList.find((item) => item.id === this.currentPost) || {}
      }
      try {
        await this.changeCurrentPostReq(USERINFO.currentPost.id)
        this.finishLogin(USERINFO)
        this.btnLoading = false
      } catch (error) {
        console.log(error)
        this.btnLoading = false
      }
    },
    /**
     * @description: 改变当前岗位
     * @param {String} 登录人id
     * @return {Promise} 接口返回对象
     */
    async changeCurrentPostReq(id) {
      const { data } = await changeCurrentPost({ postId: id })
      this.currentPostInfo = { ...data, projectId: '', projectName: '' } || {}
      if (this.currentPostInfo.code === 'PD') {
        let res2 = await getProjectIdByOrgId({ id: this.currentPostInfo.id })
        if (res2.code === 200) {
          this.currentPostInfo = {
            ...this.currentPostInfo,
            projectId: res2.data.projectId,
            projectName: res2.data.projectName
          }
        }
        let res1 = await getCurrentUserBranchCom3({ tagCodes: ['BC'] })
        if (res1.code === 200) {
          this.currentPostInfo = { ...this.currentPostInfo, ...res1.data[0] }
        }
      } else {
        let company = {
          orgId: this.currentPostInfo.id,
          orgName: this.currentPostInfo.name,
          tagCode: this.currentPostInfo.code
        }
        this.currentPostInfo = { ...this.currentPostInfo, ...company }
      }
    },
    /**
     * @description: 存储用户信息
     * @param {String} userInfo 用户id
     * @return {Void}
     */
    finishLogin(userInfo) {
      const updateUserInfo = {
        ...userInfo,
        currentPost: {
          ...this.currentPostInfo, // 这里面的id为组织机构ID
          postId: this.currentPost // 所选择岗位的id
        }
      }
      Vue.getAcloudProvider().setUserInfo(updateUserInfo)
      let level = { CO: 0, BC: 1, PD: 2 }[this.currentPostInfo.code] ?? ''
      if (level || level == 0) sessionStorage.setItem('currentLevel', level)
      this.tokenLock = false // 解开token锁
      this.userInfo = JSON.parse(sessionStorage.getItem('ycloud-user_info'))
      this.reset()
      this.visible = false
      // this.reload()
      this.$router.go(0)
    },
    /**
     * @description: 遮罩层点击关闭
     * @param {Event} 事件对象
     * @return {Void}
     */
    maskClick(e) {
      e.stopPropagation()
      this.visible = !e.target.contains(this.$refs.wrapper)
    },
    /**
     * @description: 重置
     * @param {Void}
     * @return {Void}
     */
    reset() {
      // 当前岗位id
      this.currentPost = ''
      // 当前岗位信息
      this.currentPostInfo = {}
      // 列表加载
      this.loading = true
      // 按钮加载
      this.btnLoading = false
      this.clearExtraCache()
    }
  }
}
</script>
<style lang="less" scoped>
.icon-item {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 28px;

  &:focus {
    outline: none;
  }
}
</style>
<style lang="less" scoped>
.post-select {
  width: 26px;
  height: 26px;
  overflow: hidden;
  position: relative;
  margin-right: 12px;
}

.post-select-icon {
  font-size: 20px;
  cursor: pointer;
}

.post-select-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.3);
  z-index: 999;
  display: none;
  transform-style: preserve-3d;
  perspective: 1000px;
  perspective-origin: 50% 50%;
}

@keyframes fade {
  from {
    display: block;
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.post-select-container-active {
  display: block;
  opacity: 0;
  animation: fade 0.3s ease forwards;

  .post-select-wrapper {
    animation: rotate 0.5s ease-in-out forwards;

    .post-select-content {
      animation: zoom 0.5s ease-in-out forwards;
    }
  }
}

@keyframes rotate {
  0% {
    transform: rotateX(50deg);
  }
  20% {
    transform: rotateX(50deg);
  }
  100% {
    transform: rotateX(0deg);
  }
}

@keyframes zoom {
  0% {
    transform: scale(0.6);
    opacity: 0;
  }
  20% {
    transform: scale(0.6);
    opacity: 0;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

.post-select-wrapper {
  width: 100%;
  height: 200%;
  transform: rotateX(50deg) translateY(100%);
  position: relative;
}

.post-select-content {
  width: 460px;
  height: 555px;
  transform: scale(0.6);
  background: rgba(0, 0, 0, 0.65);
  border-radius: 8px;
  padding: 50px 40px 0;
  position: absolute;
  bottom: 75%;
  left: 50%;
  margin: -277.5px -230px;
  opacity: 0;

  > img {
    width: 100%;
    object-fit: contain;
    display: block;
  }

  > p {
    font-size: 20px;
    color: #ffffff;
    font-weight: bold;
    padding: 20px 0;
    padding-bottom: 30px;
    text-align: center;
    letter-spacing: 0.2em;
    line-height: 1em;
  }

  .ant-btn-primary:hover,
  .ant-btn-primary:focus {
    background: linear-gradient(90deg, #096dd9, #00a9ff);
    border-color: #40a9ff;
  }
}

.post-select-radio {
  overflow-y: auto;
  overflow-x: hidden;
  height: 180px;

  .ant-radio-inner {
    background-color: transparent;

    &::after {
      opacity: 1;
      transform: scale(0.7);
      background-color: #ffffff;
    }
  }

  .ant-radio-wrapper {
    display: block;
    color: rgb(255, 255, 255);
    line-height: 30px;
    height: 30px;
    text-align: left;
  }

  .ant-radio-checked .ant-radio-inner {
    &::after {
      background-color: #1890ff;
    }
  }

  &::-webkit-scrollbar {
    background: transparent;
    width: 8px;
    height: 8px;
  }

  &::-webkit-scrollbar-thumb {
    width: 8px;
    border-radius: 8px;
    background: transparent;
  }
}

.post-select-empty .ant-empty-description {
  color: #ffffff;
}

.post-select-submit {
  font-size: 16px;
  height: 55px;
  color: rgb(232, 240, 254);
  background: linear-gradient(90deg, #096dd9, #00a9ff);
  margin: 20px 0;
  display: block;
  width: 100%;
  border: none;
  outline: none;
  border-radius: 4px;
  cursor: pointer;

  .anticon {
    margin-right: 10px;
  }
}
</style>
